package com.aso114.project.mvp.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.base.BaseMvpActivity;
import com.aso114.project.base.BaseSimpleActivity;
import com.aso114.project.bean.LoginBean;
import com.aso114.project.commonview.ClearEditText;
import com.aso114.project.commonview.PhoneCode;
import com.aso114.project.mvp.LoginSP;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.mvp.presenter.MainPresenter;
import com.aso114.project.mvp.view.MainView;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.PresenterFactory;
import com.aso114.project.util.PresenterLoder;
import com.aso114.project.util.SystemBarHelper;
import com.aso114.project.util.ToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 注册登陆
 */
public class LoginActivity extends BaseSimpleActivity {
    @BindView(R.id.activity_register_get_code_tv)
    TextView getCodeTv;
    int i = 60;// 倒计时的整个时间数
    @BindView(R.id.layout_title_bar_right_iv)
    ImageView layoutTitleBarRightIv;
    @BindView(R.id.pc_1)
    PhoneCode pc1;
    @BindView(R.id.submit)
    TextView submit;
    @BindView(R.id.rule)
    TextView rule;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.et_code)
    LinearLayout etCode;
    @BindView(R.id.welcome)
    TextView welcome;
    @BindView(R.id.phone)
    ClearEditText phone;
    Dialog dialog;
    @BindView(R.id.layout_title_bar_title_tv)
    TextView layoutTitleBarTitleTv;
    @BindView(R.id.layout_title_bar_back_iv)
    ImageView layoutTitleBarBackIv;
    @BindView(R.id.title_top_ly)
    RelativeLayout titleTopLy;
    private Handler mHandler = new Handler();// 全局handler
    public static LoginActivity instance; // 声明一下
    Intent intent;

    private boolean isShowCode = false;
    private boolean isTwoHierarchy = false;

    @Override
    protected int getResouseId() {
        return R.layout.login_activity;
    }

    @Override
    protected void initView() {
        SystemBarHelper.immersiveStatusBar(this);
        SystemBarHelper.setHeightAndPadding(this, titleTopLy);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SystemBarHelper.immersiveStatusBar(this, 0);
            SystemBarHelper.setStatusBarDarkMode(this);
        }
//        getSupportActionBar().hide();
        layoutTitleBarTitleTv.setText("注册/登陆");
        String str1 = String.format("注册/登陆即表示您已阅读,并同意<font color=\"#333333\">%s", "《用户注册协议》");
        rule.setText(Html.fromHtml(str1));
        instance = this;
        if (LoginSP.getInstance().getFirst().equals("")) {
            layoutTitleBarBackIv.setVisibility(View.GONE);
        }
        getCodeTv.setVisibility(View.GONE);
        etCode.setVisibility(View.GONE);
        rule.setVisibility(View.GONE);
        submit.setEnabled(false);

        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (phone.getText().toString().length() == 11) {
                    submit.setEnabled(true);

                } else {
                    submit.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getBroadcast(Context context, Intent intent) {

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @OnClick({R.id.layout_title_bar_back_iv, R.id.activity_register_get_code_tv, R.id.submit, R.id.rule})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_title_bar_back_iv:
                finish();
                break;
            case R.id.rule:

                intent = new Intent(this, NeedNoticeDetailActivity.class);
                intent.putExtra("type", "10");
                startActivity(intent);
                break;
            case R.id.activity_register_get_code_tv:
                getCode();
                break;

            case R.id.submit:
                if (!isTwoHierarchy) {
                    if (!phone.getText().toString().matches(Constant.REGEX_PHONE)) {
                        Helper.showToast("手机号格式不正确");
                        return;
                    }

                    //隐藏键盘
                    InputMethodManager imm = (InputMethodManager)
                            getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(submit.getWindowToken(), 0);


                    pc1.requestFocus();//让editText2获取焦点
                    getCodeTv.setVisibility(View.VISIBLE);
                    etCode.setVisibility(View.VISIBLE);
                    rule.setVisibility(View.VISIBLE);
                    text.setVisibility(View.GONE);
                    isTwoHierarchy = true;
//                    Drawable butom = this.getResources().getDrawable(R.drawable
//                            .edittext_line_red);//
//                    // 获取res下的图片drawable
//                    butom.setBounds(0, 0, butom.getMinimumWidth(), butom.getMinimumHeight());//
                    // 一定要设置setBounds();
                    // 调用setCompoundDrawables(Drawable left, Drawable top,Drawable right,
                    // Drawable bottom)方法。
                    // (有四个参数，不需要设置的参数传null)
                    phone.setCompoundDrawables(null, null, null, null);
                    welcome.setText("验证码已发送至");
                    submit.setText("登陆");
                    getCode();
                } else {

                    if (TextUtils.isEmpty(pc1.getPhoneCode())) {
                        ToastUtils.showToast(this, "请输入验证码");
                        return;
                    }
                    if (pc1.getPhoneCode().length() < 4) {
                        ToastUtils.showToast(this, "请输入正确验证码");
                        return;
                    }

                    final View dialogview = LoginActivity.this.getLayoutInflater().inflate(
                            R.layout.loading_view, null);
                    dialog = new Dialog(LoginActivity.this, R.style.dialogStyle);
                    dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                    dialog.getWindow().setGravity(Gravity.CENTER);
                    // 设置点击外围解散
                    dialog.setCanceledOnTouchOutside(true);
                    dialog.setCancelable(true);//设置是否可以按退回键取消
                    dialog.show();
                    TextView tv = (TextView) dialogview.findViewById(R.id.wecate);
                    tv.setText("正在登陆中...");


                    CommentModel.getInstant().getLogin(phone.getText().toString(),
                            pc1.getPhoneCode(), new CallBack() {
                                @Override
                                public void onSuccess(Object o, boolean isSuccess, String msg) {
                                    dialog.cancel();
                                    Helper.gotoLogin(isSuccess);//token失效去重新登陆

                                    LoginBean loginBean = (LoginBean) o;
                                    if (loginBean == null) {
                                        return;
                                    }
                                    LoginSP.getInstance().setToken(loginBean.getToken());
                                    LoginSP.getInstance().setUserAreaId(loginBean.getUserAreaId());
                                    LoginSP.getInstance().setUserEmail(loginBean.getUserEmail());
                                    LoginSP.getInstance().setUserId(loginBean.getUserId());
                                    LoginSP.getInstance().setUserLitpic(loginBean.getUserLitpic());
                                    LoginSP.getInstance().setUserMobile(loginBean.getUserMobile());
                                    LoginSP.getInstance().setUserName(loginBean.getUserName());
                                    LoginSP.getInstance().setCityname(loginBean.getUserAreaName());


                                    if (LoginSP.getInstance().getUserAreaId().equals("0")) {
                                        //为0表示还没选择考区 需要跳转去选择考区
                                        intent = new Intent(LoginActivity.this, ExamAddressActivity.class);
                                        startActivity(intent);
                                    } else {
                                        //已经有选择过   那么第一次登陆就可以跳转首页
                                        if (LoginSP.getInstance().getFirst().equals("")) {
                                            LoginSP.getInstance().setFirst("1");//表示不是第一次运行
                                            intent = new Intent(LoginActivity.this, MainActivity.class);
                                            startActivity(intent);

                                        } else {
                                            finish(); //平常进来的登陆，登陆后直接结束
                                        }

                                    }

                                }

                                @Override
                                public void onFailure(String fail) {
                                    dialog.cancel();
                                    Helper.showToast(fail);
                                }
                            });
                }

                break;
        }
    }

    private void getCode() {
        Constant.falg = false;
        new Thread(new ClassCut()).start();// 开启倒计时
        getCodeTv.setEnabled(Constant.falg);
        CommentModel.getInstant().getVerificationCode(phone.getText().toString(), new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                Helper.gotoLogin(isSuccess);//token失效去重新登陆
            }

            @Override
            public void onFailure(String fail) {
                Helper.showToast(fail);
            }
        });

    }


    class ClassCut implements Runnable {// 倒计时逻辑子线程

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (i > 0) {// 整个倒计时执行的循环
                i--;
                mHandler.post(new Runnable() {// 通过它在UI主线程中修改显示的剩余时间
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        getCodeTv.setTextColor(getResources().getColor(R.color.a999999));
                        getCodeTv.setText(i + "S");// 显示剩余时间
                        if (i < 0) {
                            Constant.falg = true;

                        }
                    }

                });
                try {
                    Thread.sleep(1000);// 线程休眠一秒钟 这个就是倒计时的间隔时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 下面是倒计时结束逻辑
            mHandler.post(new Runnable() {
                @Override
                public void run() {

                    getCodeTv.setEnabled(true);
                    String s = getResources().getString(R.string.getcheck);
                    // 进行业务处理
                    // TODO Auto-generated method stub
                    getCodeTv.setText(s);// 一轮倒计时结束 修改剩余时间为一分钟
                    getCodeTv.setTextColor(getResources().getColor(R.color.aff6559));

                }
            });
            i = 60;// 修改倒计时剩余时间变量为60秒
        }
    }


    // 隐藏软键盘
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub \
        InputMethodManager manager = (InputMethodManager) getSystemService(Context
                .INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null
                    && getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }


}
